﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BesAsm.Framework.Collections
{
  public static class CollectionExtensions
  {
    /// <summary>
    /// Collects all the children of the same type as an IEnumerable parent into a flat list
    /// </summary>
    /// <typeparam name="T">Type of item in collection</typeparam>
    /// <param name="source">The parent</param>
    /// <param name="DescendBy">The function determining how the children are retrieved</param>
    /// <returns></returns>
    public static IEnumerable<T> Descendants<T>(
      this IEnumerable<T> source,
      Func<T, IEnumerable<T>> DescendBy)
    {
      foreach (T value in source)
      {
        yield return value;

        foreach (T child in DescendBy(value).Descendants<T>(DescendBy))
        {
          yield return child;
        }
      }
    }
  }
}
